<script lang="ts">
/**
 * @author leo
 * @description #19514 视频新增、编辑编辑页面
 */

import { Component, Vue, Prop, Watch, Emit } from "vue-property-decorator";
import { EventBus } from "feok-lib";
import OSSFileUpload from "@/components/OSSFileUpload.vue";
import GroupSelect from "@/components/GroupSelect";
import ChoosePhoto from "@/components/ChoosePhoto";
import PhotoUpload from "@/views/archives/photo/PhotoUpload.view.vue";

import { postApiAssetsFile, putApiAssetsFileId } from "@/model";

@Component({
  components: {
    OSSFileUpload,
    GroupSelect,
    PhotoUpload,
    ChoosePhoto
  }
})
export default class UploadVideoForm extends Vue {
  get rules() {
    return {
      video: [
        { required: true, message: "此项为必填项", trigger: ["blur", "change"] }
      ],
      group_id: [
        { required: true, message: "此项为必填项", trigger: ["blur", "change"] }
      ],
      url: [
        { required: true, message: "此项为必填项", trigger: ["blur", "change"] }
      ]
    };
  }

  @Prop() public groupId!: string; // 分组Id
  @Prop() public videoId!: string; // 视频Id
  @Prop() public obj!: any; // 视频Id

  public dialogTableVisible = false;
  public dialogTableVisible2 = false;
  public vLoading = false; // 页面初始化时，loading状态
  public form = {
    name: "", // 名称
    video: "",
    size: 0,
    group_id: "", // 分组
    url: "", // 封面
    url_name: "", // 封面名称
    type: "VIDEO" // 封面名称
  };

  @Emit()
  public onCancel() {}

  /**
   * 表单验证
   */
  public checkForm() {
    return new Promise((resolve, reject) => {
      const $form = this.$refs.form as any;
      $form.validate((valid: any) => {
        if (valid) {
          resolve(true);
        } else {
          // EventBus.$emit('error', '表单验证失败');
          reject(false);
        }
      });
    });
  }

  /**
   * 拉取数据
   */
  public async fetchFormData() {
    this.vLoading = true;
    try {
      // const data = await this.getWebAuthRoleById({
      //   id: this.id,
      // });
      // 设置菜单

      this.form.group_id = this.obj.group_id;
      this.form.url = this.obj.cover;
    } catch (error) {
      // 拉取失败
      EventBus.$emit("error", "数据拉取失败，请稍后重试");
    }
    this.vLoading = false;
  }

  // 上传新图片
  public openUploadPhoto() {
    this.dialogTableVisible = true;
  }

  public onModalCancel() {
    this.dialogTableVisible = false;
  }

  public onModalDone(list: any[]) {
    this.form.url = list[0].url;
    this.onModalCancel();
  }

  // 上传新图片
  public openUploadPhoto2() {
    this.dialogTableVisible2 = true;
  }

  public onModalCancel2() {
    this.dialogTableVisible2 = false;
  }

  public onModalDone2(list: any) {
    this.form.url = list.url;
    this.onModalCancel2();
  }

  // 视频上传成功
  public onSuccess(response: any, file: any, fileList: any) {
    this.form.video = response.url;
    this.form.name = file.name;
    this.form.size = file.size;
  }

  // 视频移除
  public handleRemove(file: any, fileList: any) {
    this.form.video = "";
    this.form.name = "";
    this.form.size = 0;
  }
  /**
   * 提交表单
   */
  private async submitForm() {
    const valid = await this.checkForm(); // 表单验证
    const res = "";
    if (valid) {
      this.vLoading = true;
      try {
        if (this.videoId) {
          // 编辑
          await putApiAssetsFileId({
            id: this.videoId,
            cover: this.form.url, // 封面
            groupId: this.form.group_id // 分组ID
          });
        } else {
          // 新增
          await postApiAssetsFile({
            name: this.form.name,
            url: this.form.video,
            type: "VIDEO", // 分类 IMAGE VIDEO FILE
            size: this.form.size, // 文件大小
            cover: this.form.url, // 封面
            groupId: this.form.group_id // 分组ID
          });
        }
        EventBus.$emit("success", "操作成功");
        this.$emit("on-done");
      } catch (error) {}
      this.vLoading = false;
    }
  }

  private mounted() {
    if (this.videoId) {
      this.fetchFormData();
    }
  }
}
</script>

<template>
  <div v-loading="vLoading" class="upload_video_form">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="本地视频：" prop="video" v-if="!this.videoId">
        <OSSFileUpload
          :limit="1"
          :fileTypes="['mp4', 'ogv', 'ogg', 'webm']"
          :maxSize="1024*1024"
          @on-success="onSuccess"
          @on-remove="handleRemove"
        ></OSSFileUpload>
        <p class="mark">视频大小不超过1G，支持mp4，ogv，ogg，webm格式</p>
      </el-form-item>
      <el-form-item label="分组：" prop="group_id">
        <GroupSelect v-model="form.group_id" :query="{type: 'VIDEO'}"></GroupSelect>
      </el-form-item>
      <el-form-item label="封面：" prop="url">
        <el-button type="primary" @click="openUploadPhoto2">选择已有图片</el-button>
        <el-button type="primary" @click="openUploadPhoto">上传新图片</el-button>
        <div class="upload_video_form_img" v-show="form.url">
          <img :src="form.url" :alt="form.url_name" />
        </div>
      </el-form-item>
      <el-form-item label>
        <el-button type="primary" class="content-modal__footer__btn" @click="submitForm">保存</el-button>
        <el-button class="content-modal__footer__btn" @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      class="upload_video_form_dialog"
      title="上传新图片"
      :visible.sync="dialogTableVisible"
      append-to-body
      center
    >
      <PhotoUpload @on-cancel="onModalCancel" @on-done="onModalDone"></PhotoUpload>
    </el-dialog>

    <el-dialog
      class="upload_video_form_dialog"
      title="选择图片"
      :visible.sync="dialogTableVisible2"
      append-to-body
      center
    >
      <ChoosePhoto @on-done="onModalDone2"></ChoosePhoto>
    </el-dialog>
  </div>
</template>

<style lang="less">
.upload_video_form {
  .mark {
    font-size: 12px;
    color: #ccc;
  }
}
.upload_video_form_dialog {
  margin-top: 54px !important;
}
.upload_video_form_img {
  display: block;
  width: 200px;
  height: 200px;
  border: 1px dashed #ccc;
  margin-top: 10px;
  text-align: center;
  border-radius: 4px;
  img {
    max-width: 198px;
    max-height: 198px;
  }
}
</style>